package com.example.star.view.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;

import com.bumptech.glide.Glide;
import com.example.star.R;
import com.example.star.api_service.ApiFavorite;
import com.example.star.api_service.ApiFollow;
import com.example.star.entity.Favorite;
import com.example.star.entity.Follow;
import com.example.star.entity.Star;
import com.example.star.retrofit.ApiClient;
import com.example.star.utils.ImageZoomDialogFragment;

import java.util.jar.Attributes;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class StarDetailActivity extends AppCompatActivity {

    public static final String EXTRA_STAR = "extra_star";
    public static final String EXTRA_SINGER_NAME = "extra_singer_name";

    private static final String MORE_INFO = "更多消息";
    private static final String COLLAPSE = "收起";
    private static final String AGE_PREFIX = "年龄: ";
    private static final String BIRTH_DATE_PREFIX = "出生日期: ";
    private static final String BIRTH_PLACE_PREFIX = "出生地: ";
    private static final String NATIONALITY_PREFIX = "国籍: ";
    private static final String ACTING_EXPERIENCE_PREFIX = "演艺经历: ";
    private static final String REPRESENTATIVE_WORKS_PREFIX = "代表作品: ";
    private static final String UNKNOWN_SINGER = "未知歌手";
    private String userName;
    private boolean isCurrentlyFavorite = false; // 用于记录当前商品是否已关注
    private ImageButton followButton;
    private ImageView imageView;
    private TextView professionTextView;
    private TextView nameTextView;
    private TextView ageTextView;
    private TextView birthDateTextView;
    private TextView birthPlaceTextView;
    private TextView nationalityTextView;
    private TextView actingExperienceTextView;
    private TextView representativeWorksTextView;
    private TextView moreActingExperienceButton;
    private TextView moreRepresentativeWorksButton;
    private TextView songsText;
    private TextView messageText;

    private boolean isActingExperienceExpanded = false;
    private boolean isRepresentativeWorksExpanded = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_star_detail);

        // 获取传递过来的数据
        String imageResource = getIntent().getStringExtra("imageResource");
        String starName = getIntent().getStringExtra("starName");
        int age = getIntent().getIntExtra("age",0);
        String birthDate = getIntent().getStringExtra("birthDate");
        String birthPlace = getIntent().getStringExtra("birthPlace");
        String nationality = getIntent().getStringExtra("nationality");
        String actingExperience = getIntent().getStringExtra("actingExperience");
        String representativeWorks = getIntent().getStringExtra("representativeWorks");
        String profession = getIntent().getStringExtra("profession");

        //初始化组件
        followButton = findViewById(R.id.follow);
        imageView = findViewById(R.id.image_star_detail);
        professionTextView = findViewById(R.id.profession_text);
        nameTextView = findViewById(R.id.text_name_detail);
        ageTextView = findViewById(R.id.text_age_detail);
        birthDateTextView = findViewById(R.id.text_birth_date_detail);
        birthPlaceTextView = findViewById(R.id.text_birth_place_detail);
        nationalityTextView = findViewById(R.id.text_nationality_detail);
        actingExperienceTextView = findViewById(R.id.text_acting_experience_detail);
        representativeWorksTextView = findViewById(R.id.text_representative_works_detail);
        moreActingExperienceButton = findViewById(R.id.btn_more_acting_experience);
        moreRepresentativeWorksButton = findViewById(R.id.btn_more_representative_works);
        songsText = findViewById(R.id.songsText);
        messageText = findViewById(R.id.messageText);


        // 从 SharedPreferences 中读取用户名
        SharedPreferences sharedPreferences = getSharedPreferences("user_info", MODE_PRIVATE);
        userName = sharedPreferences.getString("username", "");

        checkFollowStatus(starName);

        followButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isCurrentlyFavorite) {
                    // 已关注，执行删除操作
                    deleteFollow(starName);
                } else {
                    // 未关注，执行关注逻辑
                    Follow follow = new Follow();
                    follow.setUserName(userName);
                    follow.setImageResource(imageResource);
                    follow.setName(starName);
                    follow.setAge(age);
                    follow.setBirthDate(birthDate);
                    follow.setBirthPlace(birthPlace);
                    follow.setNationality(nationality);
                    follow.setActingExperience(actingExperience);
                    follow.setRepresentativeWorks(representativeWorks);
                    follow.setProfession(profession);
                    // 这里需要实现保存关注的接口调用
                    saveFollow(follow);
                }
            }
        });

        nameTextView.setText(starName);
        ageTextView.setText(AGE_PREFIX + age);
        birthDateTextView.setText(BIRTH_DATE_PREFIX + birthDate);
        birthPlaceTextView.setText(BIRTH_PLACE_PREFIX + birthPlace);
        nationalityTextView.setText(NATIONALITY_PREFIX + nationality);
        actingExperienceTextView.setText(ACTING_EXPERIENCE_PREFIX + actingExperience);
        representativeWorksTextView.setText(REPRESENTATIVE_WORKS_PREFIX + representativeWorks);
        professionTextView.setText(profession);


        moreActingExperienceButton.setOnClickListener(v -> {
            toggleTextExpansion(actingExperienceTextView, moreActingExperienceButton, isActingExperienceExpanded);
            isActingExperienceExpanded = !isActingExperienceExpanded;
        });

        moreRepresentativeWorksButton.setOnClickListener(v -> {
            toggleTextExpansion(representativeWorksTextView, moreRepresentativeWorksButton, isRepresentativeWorksExpanded);
            isRepresentativeWorksExpanded = !isRepresentativeWorksExpanded;
        });


        // 先设置默认图片
        imageView.setImageResource(R.drawable.register);

        // 检查 imageResource 是否为 null
        if (imageResource != null) {
            try {
                // 尝试当作本地资源 ID 处理
                int imageResId = getResources().getIdentifier(imageResource, "drawable", getPackageName());
                if (imageResId != 0) {
                    imageView.setImageResource(imageResId);
                } else {
                    // 若不是有效的本地资源 ID，尝试使用 Glide 加载，可能是网络图片
                    Glide.with(this)
                            .load(imageResource)
                            .placeholder(R.drawable.register) // 加载中显示的图片
                            .error(R.drawable.register) // 加载失败显示的图片
                            .into(imageView);
                }
            } catch (Exception e) {
                // 出现异常，使用 Glide 加载，可能是网络图片
                Glide.with(this)
                        .load(imageResource)
                        .placeholder(R.drawable.register)
                        .error(R.drawable.register)
                        .into(imageView);
            }

            // 设置头像点击监听器(只对上传的图片有用)
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String imageUrl = imageResource;
                    ImageZoomDialogFragment dialogFragment = ImageZoomDialogFragment.newInstance(imageUrl);
                    FragmentManager fragmentManager = getSupportFragmentManager();
                    dialogFragment.show(fragmentManager, "image_zoom_dialog");
                }
            });
        }


        Star star = getStarFromIntent();
        if (star != null) {
            setupSongsButton(star);
            setupMessageButton(star);
        }
    }

    private Star getStarFromIntent() {
        return (Star) getIntent().getSerializableExtra(EXTRA_STAR);
    }


    private void setupSongsButton(Star star) {
        String profession = getIntent().getStringExtra("profession");
        if ("歌手".equals(profession)) {
            songsText.setVisibility(View.VISIBLE);
            songsText.setOnClickListener(v -> {
                String singerName = star.getName() != null ? star.getName() : UNKNOWN_SINGER;
                Intent intent = new Intent(StarDetailActivity.this, SongsActivity.class);
                intent.putExtra(EXTRA_SINGER_NAME, singerName);
                startActivity(intent);
            });
        } else {
            songsText.setVisibility(View.GONE);
        }
    }

    private void setupMessageButton(Star star) {
        messageText.setOnClickListener(v -> {
            String singerName = star.getName() != null ? star.getName() : UNKNOWN_SINGER;
            Intent intent = new Intent(StarDetailActivity.this, MessageActivity.class);
            intent.putExtra(EXTRA_SINGER_NAME, singerName);
            startActivity(intent);
        });
    }


    private void toggleTextExpansion(TextView textView, TextView button, boolean isExpanded) {
        if (isExpanded) {
            textView.setMaxLines(3);
            textView.setEllipsize(android.text.TextUtils.TruncateAt.END);
            button.setText(MORE_INFO);
        } else {
            textView.setMaxLines(Integer.MAX_VALUE);
            textView.setEllipsize(null);
            button.setText(COLLAPSE);
        }
    }

    private void checkFollowStatus(String starName) {
        ApiFollow apiFollow = ApiClient.getApiFollow();
        Call<Boolean> call = apiFollow.checkFollow(userName, starName);
        call.enqueue(new Callback<Boolean>() {
            @Override
            public void onResponse(Call<Boolean> call, Response<Boolean> response) {
                if (response.isSuccessful()) {
                    isCurrentlyFavorite = response.body();
                    if (isCurrentlyFavorite) {
                        // 更新按钮图标或文本为删除状态
                        followButton.setImageResource(R.drawable.ic_delete_24); // 假设存在删除图标资源
                    } else {
                        // 更新按钮图标或文本为关注状态
                        followButton.setImageResource(R.drawable.ic_follow_24); // 假设存在关注图标资源
                    }
                } else {
                    try {
                        String errorMessage = response.errorBody().string();
                        Toast.makeText(StarDetailActivity.this, "检查关注状态失败: " + errorMessage, Toast.LENGTH_SHORT).show();
                    } catch (Exception e) {
                        Toast.makeText(StarDetailActivity.this, "检查关注状态失败: 未知错误", Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<Boolean> call, Throwable t) {
                Toast.makeText(StarDetailActivity.this, "网络请求失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void saveFollow(Follow follow) {
        // 实现保存关注的接口调用
        ApiFollow apiFollow = ApiClient.getApiFollow();
        // 假设存在保存关注的接口方法 saveFavorite，根据实际情况调整
        Call<Follow> call = apiFollow.saveFollow(follow);
        call.enqueue(new Callback<Follow>() {
            @Override
            public void onResponse(Call<Follow> call, Response<Follow> response) {
                if (response.isSuccessful()) {
                    isCurrentlyFavorite = true;
                    // 更新按钮图标或文本为删除状态
                    followButton.setImageResource(R.drawable.ic_delete_24);
                    Toast.makeText(StarDetailActivity.this, "关注成功", Toast.LENGTH_SHORT).show();
                } else {
                    try {
                        String errorMessage = response.errorBody().string();
                        Toast.makeText(StarDetailActivity.this, "关注失败: " + errorMessage, Toast.LENGTH_SHORT).show();
                    } catch (Exception e) {
                        Toast.makeText(StarDetailActivity.this, "关注失败: 未知错误", Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<Follow> call, Throwable t) {
                Toast.makeText(StarDetailActivity.this, "网络请求失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void deleteFollow(String Name) {
        ApiFollow apiFollow = ApiClient.getApiFollow();
        Call<Void> call = apiFollow.deleteFollow(userName, Name);
        call.enqueue(new Callback<Void>() {
            @Override
            public void onResponse(Call<Void> call, Response<Void> response) {
                if (response.isSuccessful()) {
                    isCurrentlyFavorite = false;
                    // 更新按钮图标或文本为关注状态
                    followButton.setImageResource(R.drawable.ic_follow_24);
                    Toast.makeText(StarDetailActivity.this, "已取消关注", Toast.LENGTH_SHORT).show();
                } else {
                    try {
                        String errorMessage = response.errorBody().string();
                        Toast.makeText(StarDetailActivity.this, "取消关注失败: " + errorMessage, Toast.LENGTH_SHORT).show();
                    } catch (Exception e) {
                        Toast.makeText(StarDetailActivity.this, "取消关注失败: 未知错误", Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<Void> call, Throwable t) {
                Toast.makeText(StarDetailActivity.this, "网络请求失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
}